package com.king.gkrpc.client;

import com.king.gkrpc.codec.Decoder;
import com.king.gkrpc.codec.Encoder;
import com.king.gkrpc.common.utils.ReflectionUtils;
import com.king.gkrpc.transport.HttpTransportClient;
import com.king.gkrpc.transport.TransportClient;

import java.lang.reflect.Proxy;

public class RpcClient {
    private RpcClientConfig config;
    private Encoder encoder;
    private Decoder decoder;
    private TransportSelector selector;

    public RpcClient(){
        this(new RpcClientConfig());
    }

    public RpcClient(RpcClientConfig config){
        this.config = config;

        this.encoder = ReflectionUtils.newInstance(this.config.getEncoderClass());
        this.decoder = ReflectionUtils.newInstance(this.config.getDecoderClass());
        this.selector = ReflectionUtils.newInstance(this.config.getSelectorClass());

        //Wrong 3rd argument type. Found:
        // 'java.lang.Class<? extends com.king.gkrpc.transport.TransportClient>', required:
        // 'java.lang.Class<com.king.gkrpc.transport.TransportClient>'
        this.selector.init(
                this.config.getServers(),
                this.config.getConnectCount(),
                this.config.getTransportClientClass()
        );
    }

    public <T> T getProxy(Class<T> clazz){
        return (T)Proxy.newProxyInstance(
              getClass().getClassLoader(),
              new Class[]{clazz},
              new RemoteInvoker(clazz,encoder,decoder,selector)
        );
    }
}
